package net.wangds.dymodel.query;

import net.wangds.dymodel.ddl.DyModelDdlComp;
import net.wangds.dymodel.meta.entity.DyModelDefEntity;
import net.wangds.dymodel.utls.DynamicModelUtils;
import net.wangds.jdbc.comp.jdbc.JdbcComp;
import net.wangds.log.helper.LogHelper;
import net.wangds.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * .
 * <p></p>
 *
 * @author 王东石 2021/2/16 10:30.
 */
@Component
@SuppressWarnings("unused")
public class InsertParse {

    @Autowired
    private JdbcComp mmJdbc;


    @Autowired
    private DyModelDdlComp mmCmpMdl;

    @Autowired
    private QueryParse mmCmpQuery;


    @SuppressWarnings({"unchecked"})
    public <T> T insert(T obj, DyModelDefEntity def){

        StringBuilder sb = new StringBuilder();
        StringBuilder sbVals = new StringBuilder();
        List<Object> list = new ArrayList<>();

        String uuid = UUID.randomUUID().toString();

        sb.append("INSERT INTO ").append(DynamicModelUtils.toFullTableName(def))
                .append("(`id`,`ctm`,`removed`,`disable`");
        sbVals.append(" VALUES (?,?,?,?");
        list.add(uuid);
        list.add(System.currentTimeMillis());
        list.add(null);
        list.add(null);

        mmCmpMdl.foreachField(def, (f)->{
            sb.append(",").append(DynamicModelUtils.toColumnName(f));
            sbVals.append(",?");
            list.add(mmCmpMdl.fetchFieldValue(obj, f));
        });

        sb.append(" )");
        sbVals.append(" )");
        sb.append(sbVals);

        String sql = sb.toString();
        Object[] args = new Object[list.size()];
        args = list.toArray(args);

        LogHelper.dev("sql:"+sql+",args:"+ JsonUtils.toJsonStr(args));
        mmJdbc.executeUpdate(sql, args);

        return mmCmpQuery.findById(uuid, def, (Class<T>)obj.getClass());
    }

}
